import React, {
    Children,
    cloneElement,
    PureComponent
} from 'react';

import {
    View,
    StyleSheet
} from 'react-native';

import Banner from 'react-native-swiper';

interface Ref {
    onPageShow?: Function,
    onPageHide?: Function
}

interface State {
    createdPage: Array<number>
}

interface Props {
    onChange:Function
}

class FullPageScroll extends PureComponent<Props, State> {

    constructor(props:Props) {
        super(props);
    }

    static defaultProps = {
        onChange:() => {}
    }

    _refs: any = {};

    private _renderChild = (child:any, i:number) => {
        return (
            <View key={i} style={styles.item}>
                {this._checkRenderPage(child, i)}
            </View>
        )
    }

    private _checkRenderPage = (child:any, i:number) => {
        const _Props = {
            ref: (e:any) => this._refs[i] = e
        }
        return cloneElement(child, _Props)
    }

    _onIndexChanged = (page: number) => {
        this._setCreated(page)
    }

    private _setCreated = (page: number) => {
        const {
            onChange
        } = this.props;

        onChange(page);
        this._onPageHooks(page);
    }

    private _onPageHooks = (page: number) => {
        const _pages = Object.keys(this._refs) as Array<any>;
        _pages.forEach((_page: number) => {
            const {
                onPageShow,
                onPageHide
            } = this._getTabPage(_page) || {};

            if (_page == page) {
                if (onPageShow) {
                    onPageShow()
                }
            }
            else {
                if (onPageHide) {
                    onPageHide()
                }
            }
        })
    }

    private _getTabPage = (page: number) => {
        return  this._refs[page] as Ref;
    }

    render() {
        const {
            children
        } = this.props;
        return (
            <Banner
                loop={false}
                autoplay={false}
                horizontal={false}
                loadMinimal={true}
                loadMinimalSize={2}
                showsButtons={false}
                showsPagination={false}
                onIndexChanged={this._onIndexChanged}
            >
                {Children.map(children, this._renderChild)}
            </Banner>
        )
    }
}

export default FullPageScroll;

const styles = StyleSheet.create({
    item: {
        flex: 1
    }
}) as any;